﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Xml.Linq;

namespace ShoppingList
{
    public class MainViewModel : INotifyPropertyChanged
    {
        /// <summary>
        ///
        /// </summary>
        [System.Xml.Serialization.XmlIgnore]
        private const string ShoppingList = "ShoppingList.xml";

        public MainViewModel()
        {
        }

        /// <summary>
        /// The user store.
        /// </summary>
        [System.Xml.Serialization.XmlIgnore]
        private System.IO.IsolatedStorage.IsolatedStorageFile _userStorage;

        /// <summary>
        /// Gets or sets the user storage for application.
        /// </summary>
        /// <value>The user storage for application.</value>
        [System.Xml.Serialization.XmlIgnore]
        public System.IO.IsolatedStorage.IsolatedStorageFile UserStorage
        {
            get
            {
                if (_userStorage == null)
                {
                    _userStorage =
                        System.IO.IsolatedStorage.IsolatedStorageFile.GetUserStoreForApplication();
                }
                return this._userStorage;
            }
        }

        /// <summary>
        /// The serializer.
        /// </summary>
        [System.Xml.Serialization.XmlIgnore]
        private System.Xml.Serialization.XmlSerializer _serializer;

        /// <summary>
        /// Gets or sets the serializer.
        /// </summary>
        /// <value>The serializer.</value>
        [System.Xml.Serialization.XmlIgnore]
        public System.Xml.Serialization.XmlSerializer Serializer
        {
            get
            {
                if (this._serializer == null)
                {
                    this._serializer = new System.Xml.Serialization.XmlSerializer(typeof(MainViewModel));
                }
                return this._serializer;
            }

            set
            {
                this._serializer = value;
            }
        }

        //private ListViewModel _currentList;
        private int _currentListIndex;

        public int CurrentListIndex
        {
            get { return _currentListIndex; }
            set
            {
                _currentListIndex = value;

                this.OnPropertyChanged("CurrentListIndex");
            }
        }

        /// <summary>
        /// Gets or sets the Current List.
        /// </summary>
        /// <value>The Current List.</value>
        [System.Xml.Serialization.XmlIgnore]
        public ListViewModel CurrentList
        {
            get
            {
                if (this.Lists.Count == 0)
                {
                    this.Lists.Add(new ListViewModel(String.Format(Resources.NewListName, DateTime.Now.ToString())));
                }
                return this.Lists[_currentListIndex];
                //return this._currentList;
            }

            set
            {
                int index = Lists.IndexOf(value);
                if (index >= 0 && index != this._currentListIndex)
                {
                    if (Lists.Count > this._currentListIndex && Lists[this._currentListIndex] != null)
                    {
                        Lists[this._currentListIndex].Selected = false;
                    }
                    this._currentListIndex = index;

                    if (Lists[this._currentListIndex] != null)
                    {
                        Lists[this._currentListIndex].Selected = true;
                    }
                    this.OnPropertyChanged("CurrentList");
                }
                else if (this._currentListIndex < Lists.Count && Lists[this._currentListIndex] != null)
                {
                    Lists[this._currentListIndex].Selected = true;
                }
                //if (value != this._currentList)
                //{
                //    this._currentList = value;

                //    this.OnPropertyChanged("CurrentList");
                //}
            }
        }

        private ObservableCollection<ListViewModel> _lists;

        /// <summary>
        /// A collection for ItemViewModel objects.
        /// </summary>
        public ObservableCollection<ListViewModel> Lists
        {
            get
            {
                if (this._lists == null
                    )
                {
                    _lists = new ObservableCollection<ListViewModel>();
                }
                return _lists;
            }
            set
            {
                this._lists = value;

                this.OnPropertyChanged("Lists");
            }
        }

        [System.Xml.Serialization.XmlIgnore]
        public bool IsDataLoaded
        {
            get;
            private set;
        }

        /// <summary>
        /// Creates and adds a few ItemViewModel objects into the Items collection.
        /// </summary>
        public void LoadData()
        {
            if (UserStorage.FileExists(ShoppingList))
            {
                using (System.IO.IsolatedStorage.IsolatedStorageFileStream
                    stream = UserStorage.OpenFile(ShoppingList, System.IO.FileMode.Open))
                {
                    if (stream.Length > 0)
                    {
                        try
                        {
                            DeserializeModelFromStream(stream);
                            this.IsDataLoaded = true;
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show(Resources.WelcomeMessage, Resources.Welcome, MessageBoxButton.OK);
                            LoadSampleData();
                            this.IsDataLoaded = true;
                        }
                        finally
                        {
                        }
                    }
                }
            }
            else
            {
                MessageBox.Show(Resources.WelcomeMessage, Resources.Welcome, MessageBoxButton.OK);
                LoadSampleData();
                this.IsDataLoaded = true;
            }
        }

        private void DeserializeModelFromStream(System.IO.Stream stream)
        {
            MainViewModel model = Serializer.Deserialize(stream) as MainViewModel;
            this.Lists.Clear();
            this.Lists = model.Lists;
            this.CurrentList = this.Lists[model.CurrentListIndex];
        }

        public void LoadSampleData()
        {
            try
            {
                //var doc = System.Xml.Linq.XDocument.Load("SampleData/" + ShoppingList);
                using (System.IO.Stream stream = App.GetResourceStream(
                    new Uri("SampleData/" + ShoppingList, UriKind.Relative)).Stream)
                {
                    DeserializeModelFromStream(stream);
                }
            }
            catch (Exception ex)
            {
                CreateSampleData();
            }
        }

        private void CreateSampleData()
        {
            this.CurrentList.ItemsOnList.Add(new ItemViewModel() { ItemName = "Milk", Amount = 5, Price = 1.39M, Comment = "Meggle" });
            this.CurrentList.ItemsOnList.Add(new ItemViewModel() { ItemName = "Eggs", Amount = 10, Price = 0.19M, Comment = "Agrokoka" });
            this.CurrentList.ItemsOnList.Add(new ItemViewModel() { ItemName = "Bread", Amount = 1, Price = 1.1M, Comment = "Manja" });
            this.CurrentList.ItemsOnList.Add(new ItemViewModel() { ItemName = "Flour", Amount = 5, Comment = "Mlin" });
        }

        public event PropertyChangedEventHandler PropertyChanged;

        internal void OnPropertyChanged(String propertyName)
        {
            PropertyChangedEventHandler handler = PropertyChanged;
            if (null != handler)
            {
                handler(this, new PropertyChangedEventArgs(propertyName));
            }
        }

        public void SaveModel()
        {
            using (System.IO.IsolatedStorage.IsolatedStorageFileStream
                stream = UserStorage.OpenFile(ShoppingList, System.IO.FileMode.Create))
            {
                Serializer.Serialize(stream, this);
            }
            //Microsoft.Phone.Shell.ShellTileSchedule s = new Microsoft.Phone.Shell.ShellTileSchedule();
            //s.Recurrence = Microsoft.Phone.Shell.UpdateRecurrence.Onetime;
            //s.
        }

        public bool SyncWithDropBox()
        {
            //DropNet.DropNetClient cl =
            //    new DropNet.DropNetClient("ybsauqq78bmln0r", "yatb1mxh4w6qpgh", "goran.obradovic@gmail.com", "ob122321");
            //using (System.IO.IsolatedStorage.IsolatedStorageFileStream
            //        stream = UserStorage.OpenFile(ShoppingList, System.IO.FileMode.Open))
            //{
            //    cl.UploadFileAsync("/test", ShoppingList, stream,
            //        new Action<RestSharp.RestResponse>(UploadSuccess),
            //        new Action<DropNet.Exceptions.DropboxException>(UploadFailire));
            //}
            //AppLimit.CloudComputing.SharpBox.StorageProvider.DropBox.DropBoxCredentials cr =
            //    new AppLimit.CloudComputing.SharpBox.StorageProvider.DropBox.DropBoxCredentials();
            //AppLimit.CloudComputing.SharpBox.CloudStorage cs = new AppLimit.CloudComputing.SharpBox.CloudStorage();
            //new AppLimit.CloudComputing.SharpBox.StorageProvider.DropBox.DropBoxConfiguration()
            return false;
        }

        //private void LoginSuccess(DropNet.Models.UserLogin login)
        //{
        //}

        //private void UploadFailire(DropNet.Exceptions.DropboxException error)
        //{
        //}

        //private void UploadSuccess(RestSharp.RestResponse target)
        //{
        //
    }
}